import React, { useRef, useEffect } from "react"
import PropType from "prop-types";

import "./index.scss"

export default function UploadContainer(props) {

    const inputRef = useRef()

    useEffect(() => {
        const inputEl = inputRef.current
        if (props.multiple) {
            inputEl.setAttribute('multiple', '')
        }

        if (props.directory) {
            inputEl.setAttribute('webkitdirectory', '')
            inputEl.setAttribute('directory', '')
        }

    }, [props.directory, props.multiple])

    /*async function uploadFile(target) {
        const file = target.files[0]
        const fileTool = new FileTool()
        const chunkList = fileTool.chunk(file)
        const md5 =  await fileTool.md5(chunkList)

        const resp = await fileNodeApi.createUpload({
            name: file.name,
            md5: md5,
            size: file.size,
            lastModified: file.lastModified,
            chunkCount: chunkList.length,
            parentId: 0
        })

        const nodeId = resp.data

        chunkList.forEach(chunk => {
            const formData = new FormData()
            formData.append('file', chunk.file)
            formData.append('seq', chunk.seq)
            formData.append('taskId', nodeId)
            fileNodeApi.uploadChunk(formData)
        })
    }

    async function uploadFolder(target) {
        const files = target.files
        const nodeList = []

        for (let i = 0; i < files.length;i++) {
            console.log(files[i].webkitRelativePath)
            nodeList.push({
                name: files[i].name,
                path: files[i].webkitRelativePath,
                size: files[i].size,
                isDir: false,
                type: files[i].type,
                lastModified: files[i].lastModified
            })
        }

        fileNodeApi.newFileTree(1, nodeList).then(resp => {
            console.log(resp.data)
        })
    }

    async function upload({ target }) {
        if (props.directory) {
            await uploadFolder(target)
        } else {
           await uploadFile(target)
        }
    }*/

    return (
        <label className={ 'upload-container ' + props.className } style={ props.style } >
            <input style={{ display: 'none' }}
                   type={ 'file' }
                   ref={ inputRef } onChange={ ({target}) => props.upload(target.files) }
            />
            <>{ props.children }</>
        </label>
    )
}

UploadContainer.propTypes = {
    style: PropType.object,
    className: PropType.string,
    multiple: PropType.bool,
    directory: PropType.bool,
    upload: PropType.func
}

UploadContainer.defaultProps = {
    style: {},
    className: '',
    multiple: false,
    directory: false,
    upload: () => {}
}